package com.trytech.mongoocrawler.server.transport.tcp;

import com.trytech.mongoocrawler.common.transport.protocol.ProtocolDecoder;
import com.trytech.mongoocrawler.common.transport.protocol.ProtocolEncoder;
import com.trytech.mongoocrawler.common.transport.protocol.ProtocolFilterChain;
import com.trytech.mongoocrawler.common.transport.protocol.ProtocolHandler;
import com.trytech.mongoocrawler.server.CrawlerConfig;
import com.trytech.mongoocrawler.server.CrawlerContext;
import com.trytech.mongoocrawler.server.transport.CrawlerServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * Created by coliza on 2017/10/7.
 */
public class NettyTcpServer {
    private static ProtocolFilterChain filterChain;

    static {
        filterChain = new ProtocolFilterChain();
    }

    protected CrawlerConfig config;
    private CrawlerContext crawlerContext;
    private int port;

    public NettyTcpServer(CrawlerContext context, CrawlerConfig config, int port) {
        this.config = config;
        this.crawlerContext = context;
        this.port = port;
        filterChain.clear();
    }

    public void addHandler(ProtocolHandler protocolHandler) {
        filterChain.addHandler(protocolHandler);
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public void start() {
        //启动服务器端
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new ProtocolEncoder());
                            ch.pipeline().addLast(new ProtocolDecoder());
                            ch.pipeline().addLast(new CrawlerServerHandler(crawlerContext, filterChain));
                        }
                    });

            ChannelFuture f = b.bind(port).sync();
            f.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
